#include "BlockQueue.hpp"
#include <unistd.h>
#include <time.h>

void* Consumer(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    
    while (true)
    {
        // 消费
        // int data = bq->pop();
        // std::cout << "consumer pop data: " << data << std::endl;
        
        // 消费任务
        Task task = bq->pop();

        // 加工处理
        task();

        std::cout << "consumer pop data: " << task.GetTask() << "; data ret: " << task.GetResult() << " thread id: " << pthread_self() << std::endl;
        // usleep(50000);
    }
    
}

void* Productor(void* args)
{
    int len = opers.size();
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    // int data = 0;
    while (true)
    {
        // 生产
        // data++;

        // 模拟生产者获取数据
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10 + 1;
        char op = opers[rand() % len];
        Task task(data1, data2, op);

        // 生产数据到阻塞队列
        bq->push(task);
        std::cout << "productor push data: " << task.GetTask() << std::endl;

        // std::cout << "productor push data: " << data << std::endl;
        usleep(100000);
    }
    
}

int main()
{
    srand(time(nullptr));
    // BlockQueue 使用模板，可以传递对象、任务等
    // BlockQueue<int>* bq = new BlockQueue<int>();
    BlockQueue<Task>* bq = new BlockQueue<Task>();

    pthread_t c[3], p[5];      // 多生产、多消费
    for (int i = 0; i < 3; ++i)
        pthread_create(c + i, nullptr, Consumer, bq);

    for (int i = 0; i < 5; ++i)
        pthread_create(p + i, nullptr, Productor, bq);

    for (int i = 0; i < 3; ++i)
        pthread_join(c[i], nullptr);

    for (int i = 0; i < 5; ++i)
        pthread_join(p[i], nullptr);   
    delete bq;

    return 0;
}